package com.irdstudio.apicenter.console.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.irdstudio.apicenter.core.dvo.RspValue;
import com.irdstudio.apicenter.frame.core.jdbc.container.PageInfo;
import com.irdstudio.apicenter.frame.core.jdbc.container.UniKeyValueObject;
import com.irdstudio.apicenter.frame.core.jdbc.tablemodel.ITableModelDAO;
import com.irdstudio.apicenter.frame.util.BeanUtils;

/**
 * 可以所有Action的父类,主要用于取数实现公共操作
 * 
 * @author guangming.li
 * @version 1.0
 * @date 2015-06-25
 */
public class MacmsBaseAction {

	/* 数据上下文 */
	public MacmsContext context = null;

	public MacmsBaseAction() {
		context = new MacmsContext();
	}

	/**
	 * 获取所有的请求参数,放入上下文中
	 */
	public void getAllRequestData(HttpServletRequest request) {
		UniKeyValueObject uvo = new UniKeyValueObject();
		Enumeration<String> e = request.getParameterNames();
		while (e.hasMoreElements()) {
			String name = e.nextElement();
			String value1 = request.getParameter(name);
			String value = value1;
			uvo.addVariable(name, value);
		}
		context.setRequestParams(uvo);
	}

	/**
	 * 返回tablemodeldao
	 * 
	 * @return
	 */
	public ITableModelDAO getTableModelDAO() {
		return (ITableModelDAO) BeanUtils.getBean("tableModelDAO");
	}

	/**
	 * 通过PrintWriter将响应数据写入response，ajax可以接受到这个数据
	 * 
	 * @param response
	 * @param data
	 */
	public void renderJsonData(HttpServletResponse response, String data) {
		PrintWriter printWriter = null;
		try {
			printWriter = response.getWriter();
			printWriter.print(data);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (null != printWriter) {
				printWriter.flush();
				printWriter.close();
			}
		}
	}

	/**
	 * 直接将响应信息转换为JSON数据返回
	 * 
	 * @param response
	 * @param data
	 */
	public void renderJsonData(HttpServletResponse response, RspValue rspValue) {
		if (rspValue == null) {
			rspValue = new RspValue("响应信息为空!");
		}
		PrintWriter printWriter = null;
		try {
			printWriter = response.getWriter();
			System.out.println(JSON.toJSONString(rspValue));
			printWriter.print(JSON.toJSONString(rspValue));
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (null != printWriter) {
				printWriter.flush();
				printWriter.close();
			}
		}
	}

	/**
	 * 返回分页信息参数
	 * 
	 * @return
	 */
	public PageInfo getPageInfo() {

		int pageNo = 0;
		int size = 10;

		// 如果为空，说明没有分页的要求
		if (context.getRequestParams().getValue("pageNo") == null) {
			return null;
		}
		pageNo = context.getRequestParams().getIntValue("pageNo");
		size = context.getRequestParams().getIntValue("pageSize");

		PageInfo pageInfo = new PageInfo();
		pageInfo.pageIdx = pageNo > 0 ? pageNo : 1;

		return pageInfo;
	}

}
